<?php

namespace App\Admin\Controllers;

use App\Models\Product;
use App\Models\ProductAttrKey;
use App\Models\ProductAttrVal;
use App\Models\ProductSku;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\Post\DeleteAttrKey;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Redis;


class ProductSkuController extends AdminController
{
    protected $title = '商品SKU';

    protected function grid()
    {
        $grid = new Grid(new ProductSku());

        $grid->column('product_id', __('所属商品'))->display(function ($product_id) {
            $name = Product::where('id', $product_id)->value('product_name');
            return $name;
        });
        $grid->column('value', __('规格值'));
        $grid->column('original_price', __('原价'));
        $grid->column('member_price', __('会员价'));
        $grid->column('number', __('数量'));

        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->where(function ($query) {
                $pids = Product::where('product_name', 'like', "%{$this->input}%")->pluck('id');
                $query->whereIn('product_id', $pids);
            }, '商品名称');

        });

        $grid->actions(function ($actions) {
            $actions->disableDelete();
        });

        $grid->disableExport();
        $grid->disableColumnSelector();

        return $grid;
    }

    protected function detail($id)
    {
        $show = new Show(ProductSku::findOrFail($id));

        $show->field('product_id', __('所属商品'))->as(function ($product_id) {
            $name = Product::where('id', $product_id)->value('product_name');
            return $name;
        });

        $show->field('value', __('规格值'));

        $show->field('original_price', __('原价'));
        $show->field('member_price', __('会员价'));
        $show->field('number', __('数量'));

//        $show->panel()
//            ->tools(function ($tools) {
//                $tools->disableDelete();
//            });

        return $show;
    }

    protected function form()
    {
        $form = new Form(new ProductSku());

        $products = Product::select('id', 'product_name')->get();
        $productsArr = [];
        foreach ($products as $v) {
            $productsArr[$v->id] = $v->product_name;
        }

        $form->select('product_id', '所属商品')->options($productsArr);
        $form->text('value', '规格值')->required();
        $form->text('original_price', '原价')->required();
        $form->text('member_price', '会员价')->required();
        $form->text('number', '数量')->required();

        $form->footer(function ($footer) {
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
        });

        return $form;
    }
}